package com.feeyo.prophet.plugins;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 做md5数据
 * 优化后的版本，使用更现代的编码方式和更简洁的代码结构
 */
public class Md5Util {
    private static final String PREFIX = "VF";
    private static final AtomicInteger COUNTER = new AtomicInteger(0);
    private static final int COUNTER_RESET = 9999;
    private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
    public static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            sb.append(HEX_DIGITS[(b >> 4) & 0xF]);
            sb.append(HEX_DIGITS[b & 0xF]);
        }
        return sb.toString();
    }

    /**
     * 生成32位MD5
     * @param text 内容
     */
    public static String md5_32(String text) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] messageDigest = digest.digest(text.getBytes(StandardCharsets.UTF_8));
            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    /**
     * 图片转成base64 数据流
     */
    public static String getImageBase64(String imageUrl) throws Exception {
        // 使用 URI 创建 URL
        URL url = new URI(imageUrl).toURL();
        // 从 URL 获取图片输入流
        try (InputStream inputStream = url.openStream()) {
            // 将输入流转换为字节数组
            byte[] imageBytes = IOUtils.toByteArray(inputStream);
            // 将字节数组进行 Base64 编码
            String base64EncodedImage = Base64.encodeBase64String(imageBytes);
            // 构建 Data URI
            String dataUri = "data:image/png;base64," + base64EncodedImage;
            return dataUri;
        }
    }

    /**
     * 生成唯一ID的方法
     */
    public static String generate() {
        long timestamp = System.currentTimeMillis();
        int rand = ThreadLocalRandom.current().nextInt(1000);
        int count = COUNTER.getAndIncrement();
        // 重置计数器，避免溢出或过长
        if (count > COUNTER_RESET) {
            COUNTER.compareAndSet(count + 1, 0);
        }
        // 使用StringBuilder构建字符串，并手动填充随机数和计数器
        StringBuilder sb = new StringBuilder(PREFIX);
        sb.append(timestamp);
        appendPaddedNumber(sb, rand, 3);
        appendPaddedNumber(sb, count % (COUNTER_RESET + 1), 4);
        return sb.toString();
    }
    private static void appendPaddedNumber(StringBuilder sb, int num, int length) {
        String numStr = Integer.toString(num);
        for (int i = numStr.length(); i < length; i++) {
            sb.append('0');
        }
        sb.append(numStr);
    }
}
